package com.chhuang.ewcrm.ctrl;

import com.browniebytes.javafx.control.DateTimePicker;
import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.application.LPKeyBoardApp;
import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.bean.TableColumnBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WLicensePlateDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.WLicensePlate;
import com.chhuang.ewcrm.string.StringUtil;
import com.chhuang.ewcrm.thread.AddLogThread;
import com.chhuang.ewcrm.utils.UpCastTextFilter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jfoenix.controls.JFXButton;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.UnaryOperator;

/**
 * 车牌数据维护控制类
 */
public class LicensePlateController implements InitController{
    private final Logger logger = LoggerFactory.getLogger(LicensePlateController.class);

    @FXML
    private TextField licensePlateTextField;
    @FXML
    private JFXButton lpKeyBoardJFXButton;
    private StringProperty lptext = new SimpleStringProperty();//车牌字符串
    @FXML
    private TableView<WLicensePlate> licensePlateTableView;
    @FXML
    private ChoiceBox<Integer> pageSizeChiceBox;
    @FXML
    private Label pagesLabel;
    @FXML
    private Label totalLabel;
    @FXML
    private Pagination licensePlatePagination;

    @FXML
    private JFXButton saveJFXButton;
    @FXML
    private JFXButton delJFXButton;

    @FXML
    private TextField querylicensePlateTextField;

    @FXML
    private DateTimePicker createTimeStartPicker;
    private ObjectProperty<LocalDateTime> createTimeStart;

    @FXML
    private DateTimePicker createTimeEndPicker;
    private ObjectProperty<LocalDateTime> createTimeEnd;

    @FXML
    private JFXButton seachJFXButton;

    private WLicensePlateDao wLicensePlateDao = App.getSession().getMapper(WLicensePlateDao.class);

    private final QueryBean<WLicensePlate> queryBean = new QueryBean<>();

    private TableColumnBean[] tableColumnBeans = {
            new TableColumnBean("ID","wlpId",false, false),
            new TableColumnBean("车牌号","wlpNumber",true),
            new TableColumnBean("创建时间","createTime",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.TIME_FORMAT);
                }
            }
    };

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //设置车牌号格式化 大写
        UpCastTextFilter upCastTextFilter = new UpCastTextFilter();
        licensePlateTextField.setTextFormatter(new TextFormatter<>(upCastTextFilter));
        querylicensePlateTextField.setTextFormatter(new TextFormatter<>(upCastTextFilter));

        //弹出键盘输入车牌
        lpKeyBoardJFXButton.setOnAction(event -> new LPKeyBoardApp(lptext).start(new Stage()));
        //监听 车牌字符串 修改
        lptext.addListener((observableValue, s, t1) -> licensePlateTextField.setText(t1));


        //设置列
        List<TableColumn<WLicensePlate, Object>> tableColumns = new LinkedList<>();
        for (TableColumnBean tb : tableColumnBeans){
            TableColumn<WLicensePlate, Object> tableColumn = new TableColumn<>(tb.getColumnName());
            tableColumn.setCellValueFactory(new PropertyValueFactory<>(tb.getRecordName()));
            tableColumn.setSortable(tb.isSort());
            tableColumn.setVisible(tb.isVisible());
            tableColumn.setCellFactory(new Callback<>() {
                @Override
                public TableCell<WLicensePlate, Object> call(TableColumn<WLicensePlate, Object> tableColumn) {
                    TableCell<WLicensePlate, Object> cell = new TableCell<>() {
                        @Override
                        protected void updateItem(Object o, boolean b) {
                            super.updateItem(o, b);
                            if (b || o == null)
                                this.setText(null);
                            else
                                this.setText(tb.format(o));
                        }
                    };
                    cell.setAlignment(Pos.CENTER);
                    return cell;
                }
            });
            tableColumns.add(tableColumn);
        }
        licensePlateTableView.getColumns().addAll(tableColumns);

        //设置双击某一行
        licensePlateTableView.setRowFactory(tableView -> {
            TableRow<WLicensePlate> row = new TableRow<>();
            row.setOnMouseClicked(mouseEvent -> {
                if(mouseEvent.getClickCount()==2 && !row.isEmpty()){
                    WLicensePlate wLicensePlate = row.getItem();
                    licensePlateTextField.setText(wLicensePlate.getWlpNumber().toUpperCase());
                }
            });
            return row;
        });

        //设置排序
        licensePlateTableView.setSortPolicy(wCustomerTableView -> {
            ObservableList<TableColumn<WLicensePlate,?>> list = wCustomerTableView.getSortOrder();
            if(list!=null && !list.isEmpty()){
                String orderby = "";
                for (TableColumn<WLicensePlate,?> tableColumn: list){
                    String property = ((PropertyValueFactory)tableColumn.getCellValueFactory()).getProperty();
                    TableColumn.SortType sortType = tableColumn.getSortType();
                    if(sortType == TableColumn.SortType.DESCENDING) property += " desc";
                    orderby += property+",";
                }
                orderby = orderby.substring(0, orderby.length()-1);
                if(StringUtils.isNotEmpty(orderby)) queryBean.setOrderBy(orderby);
                getTableData();
            }
            return true;
        });

        //每页显示多少条数据
        pageSizeChiceBox.getItems().addAll(5,10,20,50,100,150,200);
        pageSizeChiceBox.setValue(queryBean.getPageSize());

        //获取表格数据
        getTableData();

        //分页设置
        licensePlatePagination.setMaxPageIndicatorCount(9);//数字按钮数量

        //日期选择设置
        createTimeStartPicker.setPopupPreWidth(createTimeStartPicker.getPrefWidth());
        createTimeStart = createTimeStartPicker.dateTimeProperty();
        createTimeEndPicker.setPopupPreWidth(createTimeEndPicker.getPrefWidth());
        createTimeEnd = createTimeEndPicker.dateTimeProperty();
//        createTimeStart.setValue(LocalDateTime.now());

        //初始化监听
        initListener();
    }

    //获取表格中的数据并显示
    private void getTableData() {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("create_time desc");
        }
        PageInfo<WLicensePlate> pageInfo = PageHelper.startPage(queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy()).doSelectPageInfo(() ->
                wLicensePlateDao.queryLike(queryBean.getQuery())
        );

        //总页数发生改变时从第一页开始
        if(queryBean.getPageNum()>pageInfo.getPages() && queryBean.getPageNum()!=1 ){
            queryBean.setPageNum(1);
            getTableData();
            return;
        }

        //一共多少条数据
        if(queryBean.getTotal()-pageInfo.getTotal()!=0){
            queryBean.setTotal(pageInfo.getTotal());
            totalLabel.setText(String.valueOf(queryBean.getTotal()));
        }

        //一共多少页
        if(queryBean.getPages()-pageInfo.getPages()!=0) {
            queryBean.setPages(pageInfo.getPages());
            pagesLabel.setText(String.valueOf(queryBean.getPages()));
            licensePlatePagination.setPageCount(queryBean.getPages());
        }

        licensePlateTableView.getItems().clear();
        licensePlateTableView.getItems().addAll(pageInfo.getList());
    }

    private void initListener() {
        //第页显示多少条数据选择器监听
        pageSizeChiceBox.getSelectionModel().selectedItemProperty().addListener((observableValue, integer, t1) -> {
            queryBean.setPageSize(t1);
            getTableData();
        });

        //点击分页按钮监听
        licensePlatePagination.currentPageIndexProperty().addListener((observableValue, number, t1) -> {
            queryBean.setPageNum(t1.intValue()+1);
            logger.debug("pagintion+++"+queryBean.toString());
            getTableData();
        });

        //点击保存
        saveJFXButton.setOnAction(event -> {
            String lpNumber = licensePlateTextField.getText();
            if(StringUtils.isEmpty(lpNumber)){
                return;
            }
            WLicensePlate wLicensePlate = new WLicensePlate();
            wLicensePlate.setWlpNumber(lpNumber.toUpperCase());
            List<WLicensePlate> wLicensePlates = wLicensePlateDao.query(wLicensePlate);

            Date now = new Date();
            if(wLicensePlates!=null && !wLicensePlates.isEmpty()){
                wLicensePlate = wLicensePlates.get(0);
            }else {
                wLicensePlate.setCreateTime(now);
            }

            if(StringUtils.isEmpty(wLicensePlate.getWlpId())) {
                wLicensePlateDao.insert(wLicensePlate);
                new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                        Constants.loginUser.getUsername(),
                        Constants.loginUser.getFullname(),
                        "添加新车牌："+wLicensePlate.toString())).start();
            }else {
                wLicensePlateDao.update(wLicensePlate);
                new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                        Constants.loginUser.getUsername(),
                        Constants.loginUser.getFullname(),
                        "修改车牌信息："+wLicensePlate.toString())).start();
            }

            getTableData();
            resetForm();
        });

        //点击删除
        delJFXButton.setOnAction(event -> {
            String lpNumber = licensePlateTextField.getText();
            if(StringUtils.isNotEmpty(lpNumber)){
                WLicensePlate wLicensePlate = new WLicensePlate();
                wLicensePlate.setWlpNumber(lpNumber.toUpperCase());
                List<WLicensePlate> wLicensePlates = wLicensePlateDao.query(wLicensePlate);
                if(wLicensePlates!=null && !wLicensePlates.isEmpty()){
                    new Thread(new AddLogThread(Constants.loginUser.getUserId(),
                            Constants.loginUser.getUsername(),
                            Constants.loginUser.getFullname(),
                            "删除车牌信息："+wLicensePlates.get(0).toString())).start();
                    wLicensePlateDao.deleteByEntity(wLicensePlates.get(0));
                }
                getTableData();
            }
            resetForm();
        });

        //点击查询
        seachJFXButton.setOnAction(event -> {
            WLicensePlate wLicensePlate = new WLicensePlate();
            String lpNumber = querylicensePlateTextField.getText();
            wLicensePlate.setWlpNumber(lpNumber.toUpperCase());
            if(!createTimeStartPicker.isVoid())
                wLicensePlate.setCreateTimeStart(DateUtil.localDateTime2Date(createTimeStart.get()));
            if(!createTimeEndPicker.isVoid())
                wLicensePlate.setCreateTimeEnd(DateUtil.localDateTime2Date(createTimeEnd.get()));
            queryBean.setQuery(wLicensePlate);
            getTableData();
        });
    }

    private void resetForm() {
        licensePlateTextField.clear();
    }

    @Override
    public void close() {

    }
}
